// controllers/subscription.controller.js
const SubscriptionService = require('../services/subscription.service');
const logger = require('../logger');

/**
 * 获取所有订阅计划
 */
async function getSubscriptionPlans(req, res) {
  try {
    const plans = await SubscriptionService.getSubscriptionPlans();
    res.json(plans);
  } catch (error) {
    logger.error('获取订阅计划失败', { error: error.message });
    res.status(500).json({ error: '获取订阅计划失败' });
  }
}

/**
 * 为用户创建订阅
 */
async function createSubscription(req, res) {
  try {
    const { planId, paymentMethod } = req.body;
    const userId = req.user.userId;
    
    const result = await SubscriptionService.createSubscription({
      userId,
      planId,
      paymentMethod
    });
    
    res.json(result);
  } catch (error) {
    logger.error('创建订阅失败', { error: error.message });
    res.status(500).json({ error: '创建订阅失败' });
  }
}

/**
 * 获取用户当前订阅
 */
async function getCurrentSubscription(req, res) {
  try {
    const userId = req.user.userId;
    
    const subscription = await SubscriptionService.getUserSubscription(userId);
    if (!subscription) {
      return res.status(404).json({ error: '未找到订阅信息' });
    }
    
    res.json(subscription);
  } catch (error) {
    logger.error('获取用户订阅失败', { error: error.message });
    res.status(500).json({ error: '获取用户订阅失败' });
  }
}

/**
 * 取消订阅
 */
async function cancelSubscription(req, res) {
  try {
    const { subscriptionId } = req.params;
    const userId = req.user.userId;
    
    const result = await SubscriptionService.cancelSubscription(subscriptionId, userId);
    
    res.json(result);
  } catch (error) {
    logger.error('取消订阅失败', { error: error.message });
    res.status(500).json({ error: '取消订阅失败' });
  }
}

module.exports = {
  getSubscriptionPlans,
  createSubscription,
  getCurrentSubscription,
  cancelSubscription
};